﻿using System;
using System.Data;
using System.Data.OleDb;

namespace Datos
{
    public class DatosOleDb : Datos
    {
        private static DatosOleDb _db;

        public override string ConnectionString { get; set; }

         // Constructor es 'protected' para utilizar el patron singleton
        protected DatosOleDb()
        {
        }

        public static DatosOleDb DB()
        {
            if (_db == null)
            {
                _db = new DatosOleDb();
                _db.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Delivery"].ToString();
            }
            return _db;
        }

        protected override IDbConnection CrearConnection()
        {
            return new OleDbConnection(ConnectionString);
        }

        protected override void CargarParametros(object[] parametros, IDbCommand command)
        {
            for (int i = 0; i < parametros.Length; i++)
            {
                SetearParametro(parametros[i], command);
            }
        }

        protected void SetearParametro(object parametro, IDbCommand command)
        {
            OleDbParameter parametroSeteado;
            if (parametro != null)
            {
                switch (parametro.GetType().Name)
                {
                    case "DateTime": parametroSeteado = ((OleDbCommand)command).Parameters.Add("", OleDbType.DBTimeStamp); break;
                    case "Boolean": parametroSeteado = ((OleDbCommand)command).Parameters.Add("", OleDbType.Boolean); break;
                    case "Int32": parametroSeteado = ((OleDbCommand)command).Parameters.Add("", OleDbType.Integer); break;
                    case "String": parametroSeteado = ((OleDbCommand)command).Parameters.Add("", OleDbType.VarChar); break;
                    case "Decimal": parametroSeteado = ((OleDbCommand)command).Parameters.Add("", OleDbType.Double); break;
                    default: parametroSeteado = ((OleDbCommand)command).Parameters.AddWithValue("", parametro == null ? DBNull.Value : parametro); break;
                }
                parametroSeteado.Value = parametro;
            }
            else
            {
                ((OleDbCommand)command).Parameters.AddWithValue("", DBNull.Value);
            }
        }
    }
}
